"use client";

import { MainContext } from "@/src/providers/MainProvider";
import { Box, useDisclosure, useToast } from "@chakra-ui/react";
import { useContext, useState } from "react";
import { MacroList } from "@/src/types/types.v1";
import EditMacroList from "./EditMacroList";
import { DeleteIcon } from "@/src/icons/DeleteIcon";
import { EditIcon } from "@/src/icons/EditIcon";
import { useTranslation } from "@/src/i18n";

function MacroListV2() {
  const toast = useToast();
  const {
    macro,
    selKeyIndex,
    setMouseKeys,
    mouseKeys,
    connectedMouse,
    profile,
    profileIndex,
  } = useContext(MainContext);
  const [editMacro, setEditMacro] = useState<MacroList>();
  const [editMacroIndex, setEditMacroIndex] = useState(0);

  const onEditMacro = (newMacro: MacroList) => {
    setEditMacro(newMacro);

    editMacroDlg.onOpen();
  };

  const editMacroDlg = useDisclosure();

  const onChangeMacro = async (newMacro: MacroList) => {
    setEditMacro(newMacro);
    const newMacroList = macro.changeMacro(editMacroIndex, newMacro);
    if (connectedMouse) {
      await connectedMouse.setMacro(newMacroList);

      const updatedMouseKeys = mouseKeys.map((key) => {
        if (key.type === 0x70) {
          if (key.code1 < macro.macroList.length) {
            return { ...key, code3: macro.macroList[key.code1].type };
          }
        }
        return key;
      });

      setMouseKeys(updatedMouseKeys);
      profile.updateMouseKeys(profileIndex, updatedMouseKeys);
      if (connectedMouse) {
        await connectedMouse.setMouseKeys(updatedMouseKeys, profileIndex);
      }
    }
  };

  const setMacro2Key = async (index: number) => {
    if (selKeyIndex == 0) {
      toast({
        title: t("leftBtnNoChange"),
        status: "info",
        duration: 3000,
        isClosable: true,
        colorScheme: "blue",
        position: "top",
      });
      return;
    }
    const newKey = {
      ...mouseKeys[selKeyIndex],
      keyName: macro.macroList[index].name,
      type: 0x70,
      code1: index,
      code2: 0x00,
      code3: macro.macroList[index].type,
    };
    const updatedMouseKeys = mouseKeys.map((key) =>
      key.index === selKeyIndex ? newKey : key
    );

    setMouseKeys(updatedMouseKeys);
    profile.updateMouseKeys(profileIndex, updatedMouseKeys);
    if (connectedMouse) {
      await connectedMouse.setMouseKeys(updatedMouseKeys, profileIndex);
    }
  };
  const { t } = useTranslation("");
  const onDeleteMacro = async (index: number) => {
    const updatedMouseKeys = mouseKeys.map((key) => {
      if (key.type === 0x70 && key.code1 == index) {
        // 恢复默认
        if (key.keyValue === 0) {
          return {
            ...key,
            type: 0x20,
            keyName: t("leftButton"),
            code1: 0x01,
            code2: 0x00,
            code3: 0x00,
          };
        } else if (key.keyValue === 1) {
          return {
            ...key,
            type: 0x20,
            keyName: t("rightButton"),
            code1: 0x02,
            code2: 0x00,
            code3: 0x00,
          };
        } else if (key.keyValue === 2) {
          return {
            ...key,
            type: 0x20,
            keyName: t("middleButton"),
            code1: 0x04,
            code2: 0x00,
            code3: 0x00,
          };
        } else if (key.keyValue === 3) {
          return {
            ...key,
            type: 0x20,
            keyName: t("backward"),
            code1: 0x08,
            code2: 0x00,
            code3: 0x00,
          };
        } else if (key.keyValue === 4) {
          return {
            ...key,
            type: 0x20,
            keyName: t("forward"),
            code1: 0x10,
            code2: 0x00,
            code3: 0x00,
          };
        }

        return key;
      }
      return key;
    });

    setMouseKeys(updatedMouseKeys);
    profile.updateMouseKeys(profileIndex, updatedMouseKeys);
    if (connectedMouse) {
      await connectedMouse.setMouseKeys(updatedMouseKeys, profileIndex);
    }

    macro.deleteMacro(index);
  };

  const drag = (evt: any, type: number, index: number) => {
    evt.dataTransfer.setData(
      "keyCode",
      JSON.stringify({
        type: 0x70,
        keyName: macro.macroList[index].name,
        code1: index,
        code2: 0x00,
        code3: macro.macroList[index].type,
      })
    );
  };
  return (
    <Box className="pt-4 space-y-1 h-[calc(100vh-400px)] overflow-hidden overflow-y-auto">
      {macro.macroList.map((macro, index) => (
        <Box
          key={index}
          className="flex justify-between px-2 py-1 hover:bg-[rgba(55,65,81,.7)] items-center rounded hover:cursor-pointer"
          draggable={true}
          onDragStart={(evt) => drag(evt, macro.type, index)}
          onClick={() => setMacro2Key(index)}
        >
          <Box className="w-52 text-ellipsis whitespace-nowrap overflow-hidden">
            {macro.name}
          </Box>
          <Box className="flex gap-3 items-center">
            <Box
              onClick={(evt) => {
                evt.stopPropagation();
                setEditMacroIndex(index);
                onEditMacro(macro);
              }}
              className="hover:cursor-pointer"
            >
              <EditIcon className="w-5 h-5 fill-white" />
            </Box>
            <Box
              onClick={(evt) => {
                evt.stopPropagation();
                onDeleteMacro(index);
              }}
              className="hover:cursor-pointer"
            >
              <DeleteIcon className="w-5 h-5 fill-white" />
            </Box>
          </Box>
        </Box>
      ))}
      {editMacroDlg.isOpen && editMacro && (
        <EditMacroList
          isOpen={editMacroDlg.isOpen}
          onChange={(macro) => onChangeMacro(macro)}
          onClose={editMacroDlg.onClose}
          macro={editMacro}
          checkName={(name) => macro.checkName(name)}
        />
      )}
    </Box>
  );
}

export default MacroListV2;
